var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "path", "crypto", "../../../com/configTool", "../Util/readFromDB", "../Util/readFromNet", "../Util/initDB", "../Util/saveToDB", "../Util/saveToFile", "../Util/readFromDisk", "../../../img/imgMD5", "../../../img/imgMD5"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const path_1 = __importDefault(require("path"));
    const crypto_1 = __importDefault(require("crypto"));
    const configTool_1 = __importDefault(require("../../../com/configTool"));
    const readFromDB_1 = __importDefault(require("../Util/readFromDB"));
    const readFromNet_1 = __importDefault(require("../Util/readFromNet"));
    const initDB_1 = __importDefault(require("../Util/initDB"));
    const saveToDB_1 = __importDefault(require("../Util/saveToDB"));
    const saveToFile_1 = __importDefault(require("../Util/saveToFile"));
    const readFromDisk_1 = __importDefault(require("../Util/readFromDisk"));
    const imgMD5_1 = __importDefault(require("../../../img/imgMD5"));
    const imgMD5_2 = __importDefault(require("../../../img/imgMD5"));
    let Loading = true;
    const DBName = 'tianditu-wmts';
    let TDU_Key = '';
    const vec_wUrl = 'http://t0.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default&format=tiles&tk=';
    const cva_w = 'http://t0.tianditu.gov.cn/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default.jpg&tk=';
    const img_w = 'http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default&format=tiles&tk=';
    const cia_w = 'http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default.jpg&tk=';
    const ter_w = 'http://t0.tianditu.gov.cn/ter_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=ter&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default&format=tiles&tk=';
    const cta_w = 'http://t0.tianditu.gov.cn/cta_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=cta&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default&format=tiles&tk=';
    const ibo_w = 'https://t0.tianditu.gov.cn/ibo_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
        '&LAYER=ibo&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
        '&style=default&format=tiles&tk=';
    var MapType;
    (function (MapType) {
        MapType["vec_w"] = "vec_w";
        MapType["cva_w"] = "cva_w";
        MapType["img_w"] = "img_w";
        MapType["cia_w"] = "cia_w";
        MapType["ter_w"] = "ter_w";
        MapType["cta_w"] = "cta_w";
        MapType["ibo_w"] = "ibo_w";
    })(MapType || (MapType = {}));
    let TianDiTu = {
        async init() {
            if (Loading) {
                Loading = false;
                await configTool_1.default.init();
                configTool_1.default.preservableONDB() && await (0, initDB_1.default)(DBName);
                this.setTDU_Key(configTool_1.default.config.TianDiTu.tk);
                console.info('TianDiTu 令牌：' + TDU_Key);
            }
        },
        setTDU_Key(key) {
            TDU_Key = key;
        },
        async getTileFileBuffer(mapType, TileMatrix, TileCol, TileRow) {
            await this.init();
            let err, buffer, dataSource;
            let templateUrl = '';
            if (mapType) {
                switch (mapType) {
                    case MapType.vec_w:
                        templateUrl = vec_wUrl;
                        break;
                    case MapType.cva_w:
                        templateUrl = cva_w;
                        break;
                    case MapType.img_w:
                        templateUrl = img_w;
                        break;
                    case MapType.cia_w:
                        templateUrl = cia_w;
                        break;
                    case MapType.ter_w:
                        templateUrl = ter_w;
                        break;
                    case MapType.cta_w:
                        templateUrl = cta_w;
                        break;
                    case MapType.ibo_w:
                        templateUrl = ibo_w;
                }
            }
            const url = templateUrl
                .replace('{TileMatrix}', TileMatrix.toString())
                .replace('{TileRow}', TileRow.toString())
                .replace('{TileCol}', TileCol.toString()) + TDU_Key;
            const relativePath = `\\${mapType}\\${TileMatrix}\\${TileCol}\\${TileRow}.png`;
            const fileSavePath = path_1.default.join(configTool_1.default.appBasePath, `temp/fileOut/${DBName}`, relativePath);
            [err, buffer, dataSource] = await (0, readFromDisk_1.default)({ fileSavePath, err, buffer, dataSource });
            [err, buffer, dataSource] = await (0, readFromDB_1.default)({ DBName, relativePath, err, buffer, dataSource });
            [err, buffer, dataSource] = await (0, readFromNet_1.default)({
                url, headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
                    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
                    'Upgrade-Insecure-Requests': '1',
                    'Sec-Fetch-Dest': 'document',
                    'Sec-Fetch-Mode': 'navigate',
                    'Sec-Fetch-Site': 'none',
                    'Sec-Fetch-User': '?1'
                }, err, buffer, dataSource
            });
            if (buffer) {
                const md5Str = crypto_1.default.createHash('md5').update(buffer).digest('hex');
                if (md5Str !== imgMD5_1.default.emptyPng) {
                    dataSource !== 'DB' && configTool_1.default.preservableONDB() && (0, saveToDB_1.default)({ DBName, relativePath, buffer }).then();
                    dataSource === 'Net' && configTool_1.default.preservableONFile() && (0, saveToFile_1.default)(fileSavePath, buffer).then();
                }
            }
            else {
                dataSource = 'nullServer';
                if (mapType === 'vec_w' || mapType === 'img_w' || mapType === 'ter_w') {
                    buffer = imgMD5_2.default.emptyBuffer;
                }
                else {
                    buffer = imgMD5_2.default.transparentBuffer;
                }
            }
            return [err, buffer, dataSource];
        }
    };
    exports.default = TianDiTu;
});
